using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ParserGenerator.TableCompression
{
    [Serializable]
    public sealed class CompactTableBuilder
    {
        public int Columns { get; }

        [NonSerialized]
        private ReadOnlyCollection<CompactTableRowBuilder> _rowsWrapper;
        private readonly List<CompactTableRowBuilder> _rows;
        public ReadOnlyCollection<CompactTableRowBuilder> Rows
        {
            get
            {
                if (_rowsWrapper == null)
                    _rowsWrapper = _rows.AsReadOnly();
                return _rowsWrapper;
            }
        }

        public CompactTableBuilder(int columns)
        {
            if (columns <= 0)
                throw new ArgumentOutOfRangeException(nameof(columns), SR.ColumnsMustBePositive);
            Columns = columns;
            _rows = new List<CompactTableRowBuilder>();
        }

        public CompactTableRowBuilder DefineRow()
        {
            CompactTableRowBuilder row = new CompactTableRowBuilder(_rows.Count, Columns);
            _rows.Add(row);
            return row;
        }

        public void Clear()
        {
            _rows.Clear();
        }

        public CompactTable Build()
        {
            CompactTableConstructor constructor = new CompactTableConstructor(this);
            CompactTable table = constructor.Construct();
            return table;
        }

        public sealed override string ToString()
        {
            return string.Join("\n", _rows);
        }
    }
}
